import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gongge/utils/AudioUtils.dart';
import 'package:table_calendar/table_calendar.dart';

import '../config/AppConst.dart';
import '../generated/l10n.dart';
import '../sqflite/DBManager.dart';
import '../utils/CommUtils.dart';
import '../utils/GamePageUtils.dart';
import '../utils/HelpUtils.dart';
import '../utils/SpUtils.dart';
import '../view/_OverScrollBehavior.dart';
import '../wight/My.dart';
import '../wight/PartRefreshWidget.dart';

/**
 *日历
 */
class Calendar extends StatefulWidget {
  Calendar({
    Key? key,
  }) : super(key: key);
  @override
  State<Calendar> createState() => _MyWidgetState();
}

//已经完成的complist
List<DateTime> completeList = [];

int startYear = 2022;
int startMoth = 1;
int endYear = 2022;
int endMoth = 1;
int endDay = 20;

String currentYearMoth = ''; //当前年月
bool isShowStartNew = true;

bool isComplete = false;

class _MyWidgetState extends State<Calendar> {
  @override
  void initState() {
    var dateTime = DateTime.now().toUtc();

    startYear = dateTime.year;
    startMoth = dateTime.month;
    currentYearMoth = "$startYear$startMoth";
    endYear = dateTime.year;
    endMoth = dateTime.month;
    //获取本月月底的日期。
    endDay = DateTime(startYear, startMoth + 1, 0).day;
    //测试
    //   startMoth = 7;
    // isshowLeft = true;

    isComplete = GamePageUtils().challengeComplete(false);

    //查询所有的
    DBManager().getDBAllChall().then((value) {
      if (value.isNotEmpty) {
        var dateTime2 = DateTime.fromMillisecondsSinceEpoch(value[0]);
        if (dateTime2.month < startMoth) {
          //小于这个月的月份
          isshowLeft = true;
        }
        startYear = dateTime2.year;
        startMoth = dateTime2.month;

        for (var item in value) {
          completeList.add(DateTime.fromMillisecondsSinceEpoch(item.date));
        }

        setState(() {});
      }
    });

    super.initState();
  }

  Future<bool> _requestPop() {
    isComplete ? Navigator.pop(context, 1) : Navigator.pop(context);
    return Future.value(false);
  }

  @override
  Widget build(BuildContext context) {
    double hight=CommUtils.getHeight(context);
    return WillPopScope(
        //增加返回键监听
        onWillPop: _requestPop, //增加返回键监听
        child: Scaffold(
          body: Container(
            height: double.infinity,
            width: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/bg.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: Column(
              children: [
                Image.asset('assets/images/top_leaves.png',
                    width: double.infinity,
                    height: ScreenUtil().setHeight(30),
                    fit: BoxFit.fill),
                SizedBox(
                  height: ScreenUtil().setHeight(15),
                ),
                //顶部垂直居中
                Container(
                  padding: EdgeInsets.only(left: 10),
                  height: ScreenUtil().setHeight(35),
                  child: Stack(
                    children: [
                      Align(
                        alignment: Alignment.centerLeft,
                        child: GestureDetector(
                          onTap: (() {
                            AudioUtils?.getInstance()?.play("seting_.mp3");
                            //关闭看是否完成
                            isComplete
                                ? Navigator.pop(context, 1)
                                : Navigator.pop(context);
                          }),
                          child: Image.asset('assets/images/back.png',
                              width: ScreenUtil().setWidth(40),
                              height: ScreenUtil().setWidth(35),
                              fit: BoxFit.contain),
                        ),
                      ),
                      Align(
                        alignment: Alignment.center,
                        child: CommUtils.getTextGame(context, 20,
                            S.of(context).calendar_, textColor, textbgColor),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: ScrollConfiguration(
                    behavior: OverScrollBehavior(),
                    child: Padding(
                      padding: EdgeInsets.only(
                        left: ScreenUtil().setWidth(15),
                        right: ScreenUtil().setWidth(15),
                      ),
                      child: getCalendar(),
                    ),
                  ),
                ),

               Image.asset('assets/images/botton_.png',
              width: double.infinity,height: hight*0.09, fit: BoxFit.fill),
              ],
            ),
          ),
        ));
  }

  bool isshowLeft = false;
  bool isShowRight = false;

  Widget getBox() {
    return SizedBox(height: ScreenUtil().setHeight(13));
  }

  //局部 创建GlobalKey
  GlobalKey<PartRefreshWidgetState> globalKey = new GlobalKey();

  GlobalKey<PartRefreshWidgetState> globalKey2 = new GlobalKey();
  GlobalKey<PartRefreshWidgetState> globalKey3 = new GlobalKey();

  Widget getCalendar() {
    double size = CommUtils.getHeight(context);
    double width = CommUtils.getWidth(context);
    //今日是否完成
    var todyComplete = GamePageUtils().challengeComplete(false);

    var dateTime = DateTime.now();
    var _strtimes =
        DateTime(dateTime.year, dateTime.month, dateTime.day, 0, 0, 0);
    //  var _intendtime = _strtimes .millisecondsSinceEpoch;//方法一
    //  print("zidsfs${_strtimes}");

    return Column(
      children: [
        SizedBox(
          //数越大，离下面星期就越远
          height: ScreenUtil().setHeight(size * 0.06),
        ),
        TableCalendar(
          onPageChanged: (focusedDay) {
            if (focusedDay.month == startMoth) {
              //等于当前月就隐藏
              isshowLeft = false;
            } else {
              isshowLeft = true;
            }

            if (focusedDay.month == endMoth) {
              //等于当前月就隐藏
              isShowRight = false;
            } else {
              isShowRight = true;
            }

            if (currentYearMoth == "${focusedDay.year}${focusedDay.month}") {
              isShowStartNew = true;
            } else {
              isShowStartNew = false;
            }

            // print("调用刷新");
            globalKey.currentState?.update();
            globalKey2.currentState?.update();
            globalKey3.currentState?.update();

            //  print("pageChage:${focusedDay}");
          },

          rowHeight: ScreenUtil().setHeight(size * 0.0483), //行高

          //星期设置
          daysOfWeekStyle: DaysOfWeekStyle(
            weekdayStyle: TextStyle(
                color: Color(0xffCBD2FF), fontSize: ScreenUtil().setSp(12)),
            //周末风格属性
            weekendStyle: TextStyle(
                color: Color(0xffCBD2FF), fontSize: ScreenUtil().setSp(12) //大小
                ),
          ),
          //头部设置
          headerStyle: HeaderStyle(
            titleTextStyle: TextStyle(
              color: Color(0xffCBD2FF),
            ),
            //第几周
            formatButtonTextStyle: TextStyle(
              color: Color(0xffCBD2FF),
            ),
            leftChevronMargin:
                EdgeInsets.only(left: width * 0.065, right: width * 0.18),
            rightChevronMargin: EdgeInsets.only(right: width * 0.05),
            rightChevronIcon: PartRefreshWidget(globalKey2, () {
              ///创建需要局部刷新的widget
              return isShowRight
                  ? Image.asset('assets/images/left_arrow.png',
                      width: ScreenUtil().setWidth(width * 0.04),
                      height: ScreenUtil().setWidth(width * 0.04),
                      fit: BoxFit.cover)
                  : SizedBox(
                      width: ScreenUtil().setWidth(width * 0.04),
                      height: ScreenUtil().setWidth(width * 0.04),
                    );
            }),

            leftChevronIcon: PartRefreshWidget(globalKey, () {
              ///创建需要局部刷新的widget
              return isshowLeft
                  ? Image.asset('assets/images/right_arrow.png',
                      width: ScreenUtil().setWidth(width * 0.04),
                      height: ScreenUtil().setWidth(width * 0.04),
                      fit: BoxFit.cover)
                  : SizedBox(
                      width: ScreenUtil().setWidth(width * 0.04),
                      height: ScreenUtil().setWidth(width * 0.04),
                    );
            }),

            //  //不要星期图标 否则点击报错
            formatButtonVisible: false,

            //  formatButtonDecoration: BoxDecoration(),
          ),

          //日历数字设置
          calendarStyle: CalendarStyle(
            //周六，周日
            weekendTextStyle: TextStyle(
              color: Color(0xffCBD2FF),
            ),

            //工作日
            defaultTextStyle: TextStyle(
              color: Color(0xffCBD2FF),
            ),

            outsideDaysVisible: true, //false=隐藏不是当月的
            //今天的外边距
            cellMargin: EdgeInsets.only(left: 1, top: 1, bottom: 1, right: 1),
            todayDecoration: BoxDecoration(
              //当前颜色
              // color: Color.fromRGBO(19, 115, 183, 100),
              //设置图片
              image: DecorationImage(
                image: AssetImage('assets/images/circle.png'),
              ),
              //  shape: BoxShape.circle,
            ),
            todayTextStyle: TextStyle(
              fontSize: ScreenUtil().setSp(15),
              color: todyComplete ? Colors.transparent : Color(0xffFFCB03),
            ),
          ),
          startingDayOfWeek: StartingDayOfWeek.monday, //周一开始

          locale: geteLange(),
          //  availableGestures: AvailableGestures.none, //不要左右滑动
          headerVisible: true, //头部显示

          firstDay: DateTime.utc(startYear, startMoth, 1),
          lastDay: DateTime.utc(endYear, endMoth, endDay),

          focusedDay: DateTime.now(),
          calendarBuilders:
              CalendarBuilders(defaultBuilder: (context, day, focusedDay) {
            //  print("day是：${TimeUtils.gtTime6(day)}");
            //除今天的其他日期设置
            if (completeList.contains(day)) {
              //  if (completeList.contains(TimeUtils.gtTime6(day))) {
              return Container(
                width: ScreenUtil().setWidth(size * 0.03),
                height: ScreenUtil().setWidth(size * 0.03),
                margin: EdgeInsets.only(
                    bottom: ScreenUtil().setHeight(size * 0.011)),
                child: Image.asset('assets/images/five_pointed_star.png',
                    fit: BoxFit.cover),
              );
            } else {
              return null;
            }
          }, todayBuilder: (context, day, focusedDay) {
            //今天的设置
            return todyComplete
                ? Container(
                    //今天完成
                    width: ScreenUtil().setWidth(18),
                    height: ScreenUtil().setWidth(18),
                    margin: EdgeInsets.only(
                        bottom: ScreenUtil().setHeight(size * 0.011)),
                    child: Image.asset('assets/images/five_pointed_star.png',
                        fit: BoxFit.cover))
                : null;
            // : Container(  这里设置的话上面的 todayTextStyle就不起重要了，  反之相反。
            //     //今天没完成
            //     margin: EdgeInsets.only(bottom: ScreenUtil().setHeight(4)),
            //     width: ScreenUtil().setWidth(32),
            //     height: ScreenUtil().setWidth(32),
            //     decoration: BoxDecoration(
            //       image: DecorationImage(
            //           image: AssetImage('assets/images/circle.png'),
            //           fit: BoxFit.contain),
            //     ),
            //     alignment: Alignment.center,
            //     child: AutoSizeText(
            //       day.day.toString(),
            //       style: TextStyle(
            //         fontSize: ScreenUtil().setSp(14),
            //         color: Color(0Xfff4c809),
            //       ),
            //     ),
            //   );
          }),
        ),
        PartRefreshWidget(globalKey3, () {
          ///创建需要局部刷新的widget
          return isShowStartNew
              ? (isComplete
                  ? HelpUtils().getcomplete(context)
                  : HelpUtils().getnewGame(context, callBack: ((selectIndex) {
                      // print("我的界面挑战成功了回调了${selectIndex}");
                      if (selectIndex == 1) {
                        isComplete = true;
                        print("挑战成功了");
                        globalKey3.currentState?.update();
                      }
                    })))
              : Text("");
        })
      ],
    );
  }

  String geteLange() {
    String? value = SpUtils.getInstance()?.getString(AppConst.language);
    if (value == null) {
      return 'zh';
    } else {
      return value;
    }
  }
}
